package com.hzcx.app.simplechat.ui.login.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hzcx.app.simplechat.base.BaseLoadingDialog;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.ui.main.MainActivity;
import com.hzcx.app.simplechat.ui.login.AddUserInfoActivity;
import com.hzcx.app.simplechat.ui.login.bean.LoginInfoBean;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.hzcx.app.simplechat.util.token.TokenUtils;

public class LoginUtil {

    private static BaseLoadingDialog loadingDialog;

    /**
     * 登录成功
     *
     * @param context
     * @param data
     */
    public static void loginSuccess(Activity context, LoginInfoBean data) {
        if (data.getIs_perfect() == 1) {
            // TODO: 2021/1/26 未知情况下环信可能未登出，所以多这一步
            // 如果为true，表示可以直接登录环信
            if(EMClient.getInstance().isLoggedInBefore()){
                TokenUtils.setTokenInfo(data);
                ChatUtil.getInstance().loadGroupDate();
                context.startActivity(new Intent(context, MainActivity.class));
                context.finish();
                UserInfoUtil.saveUser(data);
                return;
            }
            // 资料已填写，登录环信
            showLoading(context);
            ChatUtil.getInstance().login(data.getHxusername(), data.getHxpassword(), new EMCallBack() {
                @Override
                public void onSuccess() {
                    LogUtils.d("登录成功");
                    hideLoading();
                    TokenUtils.setTokenInfo(data);
                    ChatUtil.getInstance().loadGroupDate();
                    context.startActivity(new Intent(context, MainActivity.class));
                    context.finish();
                    UserInfoUtil.saveUser(data);
                }

                @Override
                public void onError(int i, String s) {
                    hideLoading();
                    context.runOnUiThread(() -> ToastUtils.show("IM登录失败：" + i + "  msg:" + s));
                }

                @Override
                public void onProgress(int i, String s) {

                }
            });
        } else {
            // 未填写资料，先让用户填写资料，并且不保存登录状态
            context.startActivity(new Intent(context, AddUserInfoActivity.class)
                    .putExtra(AddUserInfoActivity.INTENT_LOGIN_INFO, data));
        }
    }

    private static void showLoading(Context context) {
        loadingDialog = new BaseLoadingDialog(context);
        loadingDialog.show();
    }

    private static void hideLoading() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }
}
